package com.sijia.reggie.controller;

import com.sijia.reggie.comment.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.UUID;

/**
 * 主要处理文件的上传和下载
 * @author 杨思佳
 * @version 1.0
 */

@Slf4j
@RequestMapping("/common")
@RestController
public class CommentController {

    @Value("${reggie.path}")
    private String fileSavePath;


    /**
     * 客户端上传文件到服务器
     * @param file
     * @return
     * @throws IOException
     */
    @PostMapping("/upload")
    public R<String> upload(MultipartFile file) throws IOException {//此处的形参名必须与前端请求的name一致
        File dir = new File(fileSavePath);
        if (!dir.exists()){//目录不存在，进行创建动作
            dir.mkdir();
        }
        String originalFilename = file.getOriginalFilename();//原始文件名
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        String fileName = UUID.randomUUID().toString() + suffix ;
        file.transferTo(new File(fileSavePath + fileName));
        return R.success(fileName);
    }


    /**
     * 客户端从服务器下载文件到本地
     * 服务器通过response向客户端写入数据
     * @param response
     * @param fileName
     */
    @GetMapping("/download")
    public void download(HttpServletResponse response, @RequestParam(value = "name") String fileName){
        try {
            response.setContentType("image/jpeg");
            //从服务器磁盘读取目标文件
            FileInputStream fileInputStream = new FileInputStream(new File(fileSavePath + fileName));
            ServletOutputStream outputStream = response.getOutputStream();
            byte[] bytes = new byte[1024];
            int len;
            while ((len = fileInputStream.read(bytes)) != -1){
                outputStream.write(bytes);
                //调用flush方法将缓冲区的数据写入
                outputStream.flush();
            }
            fileInputStream.close();
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
